<template>
  <div class="app-container">
    <div class="content-container agent-container">
      <div class="welcome-header">
        <div class="welcome-text">
          <h2>工业智能体</h2>
          <p>使用智能体解决您的工业问题</p>
        </div>
        <div class="action-buttons">
          <el-button type="primary" icon="Plus" @click="handleCreateAgent"
            >创建智能体</el-button
          >
        </div>
      </div>

      <div class="agent-content-wrapper">
        <div v-loading="loading" class="agent-cards">
          <el-empty
            v-if="agentList.length === 0"
            description="暂无智能体数据"
          />
          <el-row v-else :gutter="20">
            <el-col
              :xs="24"
              :sm="12"
              :md="8"
              v-for="(item, index) in agentList"
              :key="index"
            >
              <el-card
                class="agent-card"
                shadow="hover"
                @click="handleUseAgent(item)"
              >
                <div class="agent-card-header">
                  <el-avatar
                    :size="50"
                    :src="item.avatar || ''"
                    icon="UserFilled"
                  />
                  <div class="agent-card-actions" @click.stop>
                    <el-dropdown
                      trigger="click"
                      @command="handleCommand($event, item)"
                    >
                      <span class="el-dropdown-link">
                        <el-icon><MoreFilled /></el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="edit"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item command="delete" divided
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
                <div class="agent-card-body">
                  <div class="agent-name">{{ item.title }}</div>
                  <div class="agent-desc">{{ item.description }}</div>
                </div>
                <div class="agent-card-footer">
                  <div class="agent-info">
                    <el-icon><DataAnalysis /></el-icon>
                    <span>{{ item.canvas_type }}</span>
                  </div>
                  <div class="agent-date">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDate(item.create_time) }}</span>
                  </div>
                </div>
                <div class="agent-capability">
                  <el-tag
                    v-for="(tag, i) in item.capabilities"
                    :key="i"
                    size="small"
                    :type="getTagType(i)"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="pagination-footer">
        <div v-if="agentList.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[8, 12, 24, 36]"
            :layout="'total, sizes, prev, pager, next, jumper'"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 创建/编辑智能体对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '创建智能体' : '编辑智能体'"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="agentFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="智能体名称" prop="name">
          <el-input v-model="form.title" placeholder="请输入智能体名称" />
        </el-form-item>
        <el-form-item label="智能体描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入智能体描述"
          />
        </el-form-item>
        <el-form-item label="智能体类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择智能体类型"
            style="width: 100%"
          >
            <el-option label="生产助手" value="production" />
            <el-option label="设备维护" value="maintenance" />
            <el-option label="质量检测" value="quality" />
            <el-option label="故障诊断" value="diagnosis" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联知识库" prop="datasetIds">
          <el-select
            v-model="form.datasetIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择关联的知识库"
            style="width: 100%"
          >
            <el-option
              v-for="item in datasetOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="智能体能力" prop="capabilities">
          <el-select
            v-model="form.capabilities"
            multiple
            placeholder="请选择智能体能力"
            style="width: 100%"
          >
            <el-option label="知识问答" value="qa" />
            <el-option label="数据分析" value="analysis" />
            <el-option label="故障诊断" value="diagnosis" />
            <el-option label="工艺优化" value="optimization" />
            <el-option label="预测维护" value="predictive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from "vue";
import {
  DataAnalysis,
  Calendar,
  MoreFilled,
  Plus,
} from "@element-plus/icons-vue";
import { parseTime } from "@/utils/ruoyi";
import { agentsListApi } from "@/api/knowledge/agent";

const { proxy } = getCurrentInstance();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
});

// 数据相关
const loading = ref(false);
const agentList = ref([]);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("create");
const submitLoading = ref(false);
const form = reactive({
  id: undefined,
  name: "",
  description: "",
  type: "",
  datasetIds: [],
  capabilities: [],
});
const rules = {
  name: [
    { required: true, message: "智能体名称不能为空", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  description: [
    { max: 500, message: "长度不能超过 500 个字符", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择智能体类型", trigger: "change" }],
};
const agentFormRef = ref(null);

// 知识库选项
const datasetOptions = ref([
  { value: 1, label: "设备维护知识库" },
  { value: 2, label: "生产工艺知识库" },
  { value: 3, label: "质量管理知识库" },
]);

// 格式化日期
function formatDate(timestamp) {
  return parseTime(timestamp, "{y}-{m}-{d} {h}:{i}");
}

// 获取标签类型
function getTagType(index) {
  const types = ["", "success", "warning", "danger", "info"];
  return types[index % types.length];
}

// 获取智能体列表
async function getList() {
  loading.value = true;
  try {
    const { code, data } = await agentsListApi();
    console.log(data, "data--");
    if (code === 200) {
      agentList.value = data;
    }
    loading.value = false;
  } catch (error) {
    console.log(error);
  }

  // // 模拟API调用
  // setTimeout(() => {
  //   agentList.value = [
  //     {
  //       id: 1,
  //       name: "设备维护助手",
  //       description: "帮助您诊断设备故障并提供维护建议",
  //       type: "设备维护",
  //       createTime: new Date().getTime() - 86400000 * 7,
  //       capabilities: ["故障诊断", "预测维护", "知识问答"],
  //     },
  //     {
  //       id: 2,
  //       name: "生产工艺优化师",
  //       description: "分析生产数据并提供工艺优化建议",
  //       type: "生产助手",
  //       createTime: new Date().getTime() - 86400000 * 3,
  //       capabilities: ["工艺优化", "数据分析", "预测维护"],
  //     },
  //   ];
  //   total.value = 2;
  //   loading.value = false;
  // }, 500);
}

// 处理页面大小变化
function handleSizeChange(size) {
  queryParams.pageSize = size;
  getList();
}

// 处理当前页变化
function handleCurrentChange(page) {
  queryParams.pageNum = page;
  getList();
}

// 处理创建智能体
function handleCreateAgent() {
  dialogType.value = "create";
  form.id = undefined;
  form.title = "";
  form.description = "";
  form.type = "";
  form.datasetIds = [];
  form.capabilities = [];
  dialogVisible.value = true;
  // 等待DOM更新后设置焦点
  setTimeout(() => {
    agentFormRef.value?.resetFields();
  }, 0);
}

// 处理编辑智能体
function handleEdit(row) {
  dialogType.value = "edit";
  form.id = row.id;
  form.title = row.title;
  form.description = row.description;
  form.type =
    row.type === "设备维护"
      ? "maintenance"
      : row.type === "生产助手"
      ? "production"
      : "custom";
  form.datasetIds = [1]; // 模拟数据
  form.capabilities = row?.capabilities
    .map((cap) => {
      if (cap === "故障诊断") return "diagnosis";
      if (cap === "预测维护") return "predictive";
      if (cap === "知识问答") return "qa";
      if (cap === "工艺优化") return "optimization";
      if (cap === "数据分析") return "analysis";
      return "";
    })
    .filter(Boolean);

  dialogVisible.value = true;
  // 等待DOM更新后设置焦点
  setTimeout(() => {
    agentFormRef.value?.resetFields();
  }, 0);
}

// 处理删除智能体
function handleDelete(row) {
  proxy.$modal
    .confirm(`确定要删除智能体"${row.title}"吗？`)
    .then(() => {
      // 模拟API调用
      setTimeout(() => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      }, 500);
    })
    .catch(() => {});
}

// 处理下拉菜单命令
function handleCommand(command, row) {
  switch (command) {
    case "edit":
      handleEdit(row);
      break;
    case "delete":
      handleDelete(row);
      break;
    default:
      break;
  }
}

// 处理使用智能体
function handleUseAgent(row) {
  proxy.$modal.msgInfo(`即将启动智能体：${row.title}`);
  // 这里可以跳转到智能体对话页面
  console.log("使用智能体", row);
}

// 提交表单
function submitForm() {
  agentFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      // 模拟API调用
      setTimeout(() => {
        submitLoading.value = false;
        proxy.$modal.msgSuccess(
          dialogType.value === "create" ? "创建成功" : "修改成功"
        );
        dialogVisible.value = false;
        getList();
      }, 1000);
    }
  });
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.content-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.welcome-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;
}

.welcome-text h2 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #303133;
}

.welcome-text p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 卡片相关样式 */
.agent-cards {
  margin-bottom: 0;
}

.el-row {
  row-gap: 24px;
  margin-bottom: 0 !important;
}

.el-col {
  padding-bottom: 0;
  margin-bottom: 0;
}

.agent-card {
  height: 100%;
  border-radius: 8px;
  transition: all 0.2s;
  cursor: pointer;
  padding: 20px;
  display: flex;
  flex-direction: column;
  margin: 0;
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.agent-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.agent-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.agent-card-actions {
  cursor: pointer;
}

.agent-card-body {
  flex: 1;
  padding: 15px 0;
  display: flex;
  flex-direction: column;
  min-height: 80px;
}

.agent-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.agent-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 0;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.agent-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.agent-info,
.agent-date {
  display: flex;
  align-items: center;
  gap: 4px;
}

.agent-capability {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 分页相关样式 */
.pagination-footer {
  margin-top: 10px;
  padding: 15px 0;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
  position: sticky;
  bottom: 0;
  z-index: 10;
  width: 100%;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.agent-content-wrapper {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 6px; /* 为滚动条预留空间 */
  padding-bottom: 20px; /* 为分页腾出空间 */
}

/* 美化滚动条 */
.agent-content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.agent-content-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.agent-content-wrapper::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style> 